import React, { useState, useEffect } from 'react';
import { workAPI } from '../services/api';

function ArticleManagement() {
  const [articles, setArticles] = useState([]);
  const [loading, setLoading] = useState(true);
  const [currentPage, setCurrentPage] = useState(1);
  const [totalPages, setTotalPages] = useState(1);
  const pageSize = 10;

  useEffect(() => {
    fetchArticles();
  }, [currentPage]);

  const fetchArticles = async () => {
    try {
      setLoading(true);
      const response = await workAPI.getWorks(currentPage, pageSize);
      
      if (response && response.result) {
        setArticles(response.result.records || []);
        setTotalPages(Math.ceil((response.result.total || 0) / pageSize));
      }
    } catch (error) {
      console.error('获取文章列表失败:', error);
      alert('获取文章列表失败，请稍后重试');
    } finally {
      setLoading(false);
    }
  };

  const handleDeleteArticle = async (workId, title) => {
    if (!alert(`确定要删除文章"${title}"吗？此操作不可撤销。`)) {
      return;
    }

    try {
      const response = await workAPI.deleteWork(workId);
      
      if (response && (response.code === 200 || response.success)) {
        alert('文章删除成功');
        fetchArticles(); // 刷新列表
      } else {
        alert(response?.message || '删除失败，请稍后重试');
      }
    } catch (error) {
      console.error('删除文章失败:', error);
      alert('删除失败，请稍后重试');
    }
  };

  const handlePageChange = (newPage) => {
    if (newPage >= 1 && newPage <= totalPages) {
      setCurrentPage(newPage);
    }
  };

  return (
    <div className="article-management">
      <div className="management-header">
        <h3>文章管理</h3>
        <button className="refresh-btn" onClick={fetchArticles}>
          刷新列表
        </button>
      </div>

      {loading ? (
        <div className="loading">加载中...</div>
      ) : (
        <>
          <div className="articles-list">
            {articles.length === 0 ? (
              <div className="no-articles">暂无文章</div>
            ) : (
              <div className="articles-table">
                <div className="table-header">
                  <span className="col-title">标题</span>
                  <span className="col-author">作者</span>
                  <span className="col-date">创建时间</span>
                  <span className="col-status">状态</span>
                  <span className="col-actions">操作</span>
                </div>
                
                {articles.map((article) => (
                  <div key={article.workId} className="table-row">
                    <span className="col-title">{article.title}</span>
                    <span className="col-author">{article.authorName || '未知作者'}</span>
                    <span className="col-date">
                      {new Date(article.createTime).toLocaleDateString()}
                    </span>
                    <span className="col-status">
                      <span className="status-badge active">已发布</span>
                    </span>
                    <span className="col-actions">
                      <button 
                        className="action-btn view-btn"
                        onClick={() => window.open(`/article/${article.workId}`, '_blank')}
                      >
                        查看
                      </button>
                      <button 
                        className="action-btn delete-btn"
                        onClick={() => handleDeleteArticle(article.workId, article.title)}
                      >
                        删除
                      </button>
                    </span>
                  </div>
                ))}
              </div>
            )}
          </div>

          {/* 分页 */}
          {totalPages > 1 && (
            <div className="pagination">
              <button 
                className="page-btn"
                onClick={() => handlePageChange(currentPage - 1)}
                disabled={currentPage === 1}
              >
                上一页
              </button>
              
              <span className="page-info">
                第 {currentPage} 页，共 {totalPages} 页
              </span>
              
              <button 
                className="page-btn"
                onClick={() => handlePageChange(currentPage + 1)}
                disabled={currentPage === totalPages}
              >
                下一页
              </button>
            </div>
          )}
        </>
      )}
    </div>
  );
}

export default ArticleManagement;
